package com.linewow.xhyy.nihaonew.fragment;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.canyinghao.candialog.CanDialog;
import com.canyinghao.candialog.CanDialogInterface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.DemoHelper;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.activity.SearchBeginActivity;
import com.linewow.xhyy.nihaonew.activity.TagListActivity;
import com.linewow.xhyy.nihaonew.adapter.FindTopicAdapter;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseEntity;
import com.linewow.xhyy.nihaonew.base.BaseInfo;
import com.linewow.xhyy.nihaonew.base.ListBaseFragment;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.NiHaoVersionEntity;
import com.linewow.xhyy.nihaonew.entity.topic.FindTopicInfo;
import com.linewow.xhyy.nihaonew.entity.image.ImagesInfo;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.util.CommonUtil;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.linewow.xhyy.nihaonew.view.XListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import okhttp3.Call;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/8/23.
 * 话题发现
 */
public class FindFragment extends ListBaseFragment implements XListView.IXListViewListener {
    private ImageView right,left;
    private TextView midTextView;
    private FindTopicAdapter findTopicAdapter;
    private String TAG = "FindFragment";
    private Type findTopicType;
    private List<FindTopicInfo<ImagesInfo,Uinfo>>findTopicInfos;
    private Gson gson;
    private PtrFrameLayout ptr;
    private View toolBarView;
    private View contentView;
    private XListView findListView;
    private int page=0;
    private NiHaoHelper niHaoHelper;

    @Override
    public void initList() {
        super.initList();
        EventBus.getDefault().register(FindFragment.this);
        findTopicType=new TypeToken<BaseInfo<FindTopicInfo<ImagesInfo,Uinfo>>>(){}.getType();
        gson=new Gson();

        niHaoHelper=NiHaoHelper.getInstance();
        requestInfo();
        requestVersionInfo();
    }

    private void requestVersionInfo() {


        String versionName= CommonUtil.getVersion(FindFragment.this.getActivity());
        Log.e(TAG,"开始版本控制的请求"+versionName);
        NiHaoOkgo.getVersion(versionName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<BaseEntity<NiHaoVersionEntity>, NiHaoVersionEntity>() {
                    @Override
                    public NiHaoVersionEntity call(BaseEntity<NiHaoVersionEntity> niHaoVersionEntityBaseEntity) {
                        return niHaoVersionEntityBaseEntity.data;
                    }
                })
                .subscribe(new Action1<NiHaoVersionEntity>() {
                    @Override
                    public void call(NiHaoVersionEntity niHaoVersionEntity) {
                        Log.e(TAG, "版本" + niHaoVersionEntity);
                        if (niHaoVersionEntity.is_update.equals("1")) {
                            if (niHaoVersionEntity.fangshi.equals("强制")) {
                                Log.e(TAG, "强制更新了");
                                showVersionDialog(niHaoVersionEntity);
                            } else {
                                if(niHaoHelper.getVersionNumber()==null){
                                    Log.e(TAG,"没有存储");
                                    showVersionDialog(niHaoVersionEntity);
                                }else{
                                    if (!niHaoHelper.getVersionNumber().equals(niHaoVersionEntity.version_number)) {
                                        Log.e(TAG, "普通更新了");
                                        showVersionDialog(niHaoVersionEntity);
                                    }
                                }

                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG,"无网络或者空指针");
                    }
                });
    }

    private void showVersionDialog(final NiHaoVersionEntity niHaoVersionEntity) {
        //如果强制的话就不显示  忽略此版本了
        if(niHaoVersionEntity.fangshi.equals("强制")){
            new CanDialog.Builder(FindFragment.this.getActivity())
                    .setTitle(getString(R.string.message_update))
                    .setMessage(niHaoVersionEntity.updated_instructions)
                    .setNegativeButton(getString(R.string.widget_cancel), true, new CanDialogInterface.OnClickListener() {
                        @Override
                        public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                            Log.e(TAG,"取消了");
                            if(niHaoVersionEntity.fangshi.equals("强制")){
                                Log.e(TAG,"强制退出");
                                getActivity().finish();
                            }
                        }
                    })
                    .setPositiveButton(getString(R.string.widget_sure), true, new CanDialogInterface.OnClickListener() {
                        @Override
                        public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                            Log.e(TAG,"选择了");
                            starDownloadLink(HttpModel.HOMEDOWNLOAD);
                        }
                    })
                    .setTileAnimator()
                    .setCancelable(false)
                    .setCircularRevealAnimator(CanDialog.CircularRevealStatus.TOP_LEFT)
                    .show();

        }else{

            new CanDialog.Builder(FindFragment.this.getActivity())
                    .setTitle(getString(R.string.message_update))
                    .setMessage(niHaoVersionEntity.updated_instructions)
                    .setNegativeButton(getString(R.string.widget_cancel), true, new CanDialogInterface.OnClickListener() {
                        @Override
                        public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                            Log.e(TAG,"取消了");
                            if(niHaoVersionEntity.fangshi.equals("强制")){
                                Log.e(TAG,"强制退出");
                                getActivity().finish();
                            }
                        }
                    })
                    .setPositiveButton(getString(R.string.widget_sure), true, new CanDialogInterface.OnClickListener() {
                        @Override
                        public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                            Log.e(TAG,"选择了");
                            starDownloadLink(HttpModel.HOMEDOWNLOAD);
                        }
                    })
                    .setNeutralButton(getString(R.string.widget_ignore_update), true, new CanDialogInterface.OnClickListener() {
                        @Override
                        public void onClick(CanDialog dialog, int checkItem, CharSequence text, boolean[] checkItems) {
                            Log.e(TAG,"记录忽略的版本"+niHaoVersionEntity.version_number);
                            niHaoHelper.setVersionNumber(niHaoVersionEntity.version_number);
                        }
                    })
                    .setTileAnimator()
                    .setCancelable(false)
                    .setCircularRevealAnimator(CanDialog.CircularRevealStatus.TOP_LEFT)
                    .show();


        }
    }

    private void starDownloadLink(String shareurl) {
        Uri uri=Uri.parse(shareurl);
        Intent intent=new Intent(Intent.ACTION_VIEW,uri);
        startActivity(intent);
    }


    /**
     *
     * @return
     */
    @Override
    protected boolean aboutFlag() {
        return false;
    }



    private void requestInfo() {
        onLoadingView();
        pullDown();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(FindFragment.this);
        ButterKnife.unbind(this);
    }



    @Override
    public void setUpView() {
        super.setUpView();
        contentView=View.inflate(getActivity(),R.layout.view_refresh_listview,null);
        toolBarView=View.inflate(getActivity(),R.layout.include_toolbar_find,null);
        right= (ImageView) toolBarView.findViewById(R.id.toolbar_find_right);
        left= (ImageView) toolBarView.findViewById(R.id.toolbar_find_left);
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent1=new Intent(getActivity(), SearchBeginActivity.class);
                startActivity(intent1);
            }
        });
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), TagListActivity.class);
                startActivity(intent);
            }
        });
        midTextView= (TextView) toolBarView.findViewById(R.id.toolbar_find_title);
        findListView= (XListView) contentView.findViewById(R.id.view_refresh_listview_view);
        findListView.setXListViewListener(FindFragment.this);

        ptr= (PtrFrameLayout) contentView.findViewById(R.id.view_refresh_listview_ptr);
        final MaterialHeader header = new MaterialHeader(getContext());
        int[] colors = getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPtrFrameLayout(ptr);
        ptr.setHeaderView(header);
        ptr.addPtrUIHandler(header);
        ptr.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame,content,header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pullDown();
            }
        });
        listBaseInclude.addView(toolBarView);
        listBaseContent.addView(contentView);
    }
    @Subscriber(tag = "refresh",mode = ThreadMode.MAIN)
    public void refreshMessage(MessageEvent messageEvent){
        Log.e(TAG,"刷新了");
        requestInfo();
    }


    @Subscriber(tag = "FindTopicAdapter",mode = ThreadMode.MAIN)
    public void onAttentionChange(MessageEvent messageEvent){
        if(!FindFragment.this.isResumed()){
            return;
        }
        final int index=messageEvent.getIndex();
        final FindTopicInfo<ImagesInfo, Uinfo>findTopicInfo=findTopicInfos.get(index);
        boolean isFllow=findTopicInfo.isfollow;
        if(!NiHaoApp.flag){
            DemoHelper.getInstance().onConnectionConflict();
            return;
        }

        if(isFllow){
            OkHttpUtils.get()
                    .url(HttpModel.USERUFOLLOW)
                    .addParams("touid",findTopicInfo.uid)
                    .addParams("token", NiHaoApp.token)
                    .build()
                    .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG,"网络请求失败"+e.getMessage());
                        }

                        @Override
                        public void onResponse(NiHaoEntity response, int id) {
                            Log.e(TAG,"取消结果返回"+response);
                            if(response.status){
                                findTopicInfo.setIsfollow(false);
                                Log.e(TAG,"部分更新了"+findTopicInfo.isfollow);
                                updateView(index);
                            }
                        }
                    });
        }else{
            OkHttpUtils.get()
                    .url(HttpModel.USERFOLLOW)
                    .addParams("touid",findTopicInfo.uid)
                    .addParams("token", NiHaoApp.token)
                    .build()
                    .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG,"网络请求失败"+e.getMessage());
                        }
                        @Override
                        public void onResponse(NiHaoEntity response, int id) {
                            Log.e(TAG,"关注结果返回"+response);
                            if(response.status){
                                findTopicInfo.setIsfollow(true);
                                updateView(index);
                                String content=getActivity().getResources().getString(R.string.message_attention_content);
                                NiHaoHelper.getInstance().requestAttention(findTopicInfo.uid,content,findTopicInfo.uid);//这里传什么rid
                            }
                        }
                    });
        }
    }
    @Override
    public void onLoadMore() {
        pullUp();
    }

    private void pullUp() {
        page++;
        OkHttpUtils.get().url(HttpModel.TOPICFIND2+ NiHaoApp.token+"&page="+page)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        onNoInternetView();
                        findListView.stopLoadMore();
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        findListView.stopLoadMore();
                        BaseInfo<FindTopicInfo<ImagesInfo,Uinfo>> baseInfo=gson.fromJson(response,findTopicType);
                        if(findTopicAdapter!=null){
                            if(baseInfo.data.size()==10){
                                findTopicInfos.addAll(baseInfo.data);
                                findTopicAdapter.notifyDataSetChanged();
                            }else{
                                findTopicInfos.addAll(baseInfo.data);
                                findTopicAdapter.notifyDataSetChanged();
                                findListView.setPullLoadEnable(false);//不能在刷新了
                            }

                        }

                    }
                });
    }


    private void pullDown() {
        page=0;
        OkHttpUtils.get().url(HttpModel.TOPICFIND1+ NiHaoApp.token+"&page="+page)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        onNoInternetView();
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.e(TAG,"打印"+response);
                        finishLoadingView();//gone掉缓冲圈
                        ptr.refreshComplete();


                        BaseInfo<FindTopicInfo<ImagesInfo,Uinfo>> baseInfo=gson.fromJson(response,findTopicType);
                        if(findTopicAdapter==null){
                            findTopicInfos=baseInfo.data;
                            findTopicAdapter = new FindTopicAdapter(findTopicInfos, getActivity());
                            findListView.setAdapter(findTopicAdapter);
                        }else{
                            findTopicInfos.clear();
                            findTopicInfos.addAll(baseInfo.data);
                            findTopicAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }


    private void updateView(int index){
        int visiblePosition = findListView.getFirstVisiblePosition();
        if (index - visiblePosition >= 0) {
            //得到要更新的item的view
            View view = findListView.getChildAt(index - visiblePosition);
            //调用adapter更新界面
            findTopicAdapter.updateView(view, index);
        }
    }

}
